import cv2
import numpy as np
import logging

# 设置日志
def setup_logger():
    logger = logging.getLogger('EdgeDetection')
    if not logger.handlers:
        logger.setLevel(logging.INFO)
        handler = logging.StreamHandler()
        handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
        logger.addHandler(handler)
    return logger

logger = setup_logger()

def apply_canny_edge_detection(image, low_threshold=30, high_threshold=100, kernel_size=5, sigma=0.8):
    """
    应用Canny边缘检测算法
    
    Args:
        image: 输入图像 (BGR格式)
        low_threshold: Canny算法的低阈值
        high_threshold: Canny算法的高阈值
        kernel_size: 高斯模糊的核大小
        sigma: 高斯模糊的标准差
        
    Returns:
        检测到的边缘图像 (白色背景，黑色边缘)
    """
    # 检查图像有效性
    if image is None or image.size == 0:
        logger.warning("收到无效图像")
        return np.ones((100, 100), dtype=np.uint8) * 255
    
    try:
        logger.info("开始Canny边缘检测...")
        
        # 转换为灰度图
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        
        # 应用高斯模糊减少噪声
        if kernel_size % 2 == 0:  # 确保核大小为奇数
            kernel_size += 1
        blurred = cv2.GaussianBlur(gray, (kernel_size, kernel_size), sigma)
        
        # 应用Canny边缘检测
        edges = cv2.Canny(blurred, low_threshold, high_threshold)
        
        # 使用形态学闭运算优化边缘
        morph_kernel = np.ones((2, 2), np.uint8)
        edges = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, morph_kernel, iterations=1)
        
        # 反转颜色（黑色边缘，白色背景）
        result = cv2.bitwise_not(edges)
        
        logger.info("Canny边缘检测完成")
        return result
        
    except Exception as e:
        logger.error(f"Canny边缘检测出错: {str(e)}")
        import traceback
        logger.error(traceback.format_exc())
        return np.ones((image.shape[0], image.shape[1]), dtype=np.uint8) * 255  # 返回空白图像

if __name__ == "__main__":
    # 测试代码
    import os
    
    # 创建测试图像 - 一个简单的形状
    test_image = np.ones((500, 500, 3), dtype=np.uint8) * 255  # 白色背景
    cv2.rectangle(test_image, (100, 100), (300, 300), (0, 0, 255), -1)  # 红色矩形
    cv2.circle(test_image, (400, 400), 50, (0, 255, 0), -1)  # 绿色圆形
    
    # 应用Canny边缘检测
    edge_image = apply_canny_edge_detection(test_image)
    
    # 保存结果
    os.makedirs("results", exist_ok=True)
    cv2.imwrite("results/test_image.png", test_image)
    cv2.imwrite("results/edge_image.png", edge_image)
    
    print("边缘检测测试完成，结果已保存到 results 目录") 